package com.achen.service.impl;

import com.achen.constant.RedisConstant;
import com.achen.dao.SetmealDao;
import com.achen.entity.PageResult;
import com.achen.entity.QueryPageBean;
import com.achen.pojo.CheckGroup;
import com.achen.pojo.Setmeal;
import com.achen.service.SetmealService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 体检套餐服务
 *
 * @author achen
 * @create 2020-04-10 10:08
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetMealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;  //从属性文件中读取要生成的html对应的目录

    @Override
    public void addSetmeal(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.addSetmeal(setmeal);
        //获取套餐id，用于简历两表的关系
        Integer setmealId = setmeal.getId();
        System.out.println(setmealId);
        //调用setSetMwalAndCheckGroup方法
        this.setSetmealAndCheckGroup(setmealId, checkgroupIds);

        //将不是垃圾图片的图片存到redis中的setmealPicDbResources集合中
        String fileName = setmeal.getImg(); //获取图片名
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成当前添加方法所需的静态页面
    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> list = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList); //与mobile_setmeal.ftl对应
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    //生成套餐详情静态页面（多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map<String, Object> dataMap = new HashMap<>();
            //为模板提供对应id所有数据
            dataMap.put("setmeal", setmealDao.findSetmealDetailById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", dataMap);
        }
    }

    /**
     * 通用的方法，用于生成静态页面
     *
     * @param templateName freeMarker模板名
     * @param htmlPageName 生成后的页面名
     * @param dateMap      页面所需数据
     */
    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> dateMap) {
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            //选定生成模板
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            File docFile = new File(outPutPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
            //输出文件
            template.process(dateMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage(); //当前页
        Integer pageSize = queryPageBean.getPageSize(); //每页显示的记录数
        String queryString = queryPageBean.getQueryString(); //查询条件

        //分页
        PageHelper.startPage(currentPage, pageSize);

        Page<CheckGroup> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findSetmealDetailById(int id) {
        return setmealDao.findSetmealDetailById(id);
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCountAndName() {
        return setmealDao.findSetmealCountAndName();
    }

    //设置套餐和检查组的多对多的关系，t_setmeal_checkgroup表
    public void setSetmealAndCheckGroup(Integer setmealId, Integer[] checkgroupIds) {
        //添加检查组和检查项的关联表(多对多)
        Map<String, Integer> map = null;
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                //添加到t_checkgroup_checkitem
                setmealDao.addSetmealAndCheckGroup(map);
            }
        }
    }
}
